package com.andox.fn.inf.rpc.rest.cluster.loadbalance;

import java.util.List;

import com.andox.fn.inf.rpc.rest.RpcRequest;
import com.andox.fn.inf.rpc.rest.RpcResponse;
import com.andox.fn.inf.rpc.rest.common.ObjectHolder;
import com.andox.fn.inf.rpc.rest.config.InterfaceConfig;
import com.andox.fn.inf.rpc.rest.config.ReferenceConfig;
import com.andox.fn.inf.rpc.rest.extension.ExtensionLoader;
import com.andox.fn.inf.rpc.rest.filter.Invoker;
import com.google.common.collect.Lists;

public class ClusterInvoker implements Invoker{

	private ReferenceConfig referenceConfig;
	
	private ObjectHolder<List<Invoker>> invokers = new ObjectHolder<List<Invoker>>();
	
	private InvokerSelector invokerSelector;
	
	public ClusterInvoker(ReferenceConfig referenceConfig){
		this.referenceConfig = referenceConfig;
		this.invokerSelector = ExtensionLoader.getExtensionLoader(InvokerSelector.class).getExtension(referenceConfig.getLoadbalance());
	}
	
	@Override
	public InterfaceConfig getConfig() {
		return this.referenceConfig;
	}

	@Override
	public RpcResponse invoke(RpcRequest request) {
		List<Invoker> invokerList = invokers.get();
		return invokerSelector.selectInvoker(invokerList).invoke(request);
	}

	public void setInvokers(List<Invoker> invokers) {
		List<Invoker> invokerx = Lists.newArrayList(invokers);
		this.invokers.set(invokerx);
	}
}
